<template>
	<el-card class="full-card">
		<div class="stock-in-record">
			<!-- 查询表单 -->
			<el-form :model="searchForm" :inline="true" class="search-form">
				<el-form-item label="商品码">
					<el-input
						v-model="searchForm.itemCode"
						placeholder="请输入商品码"
						clearable
						@keyup.enter="handleSearch"
					/>
				</el-form-item>
				<el-form-item label="条形码">
					<el-input
						v-model="searchForm.barcode"
						placeholder="请输入条形码"
						clearable
						@keyup.enter="handleSearch"
					/>
				</el-form-item>
				<el-form-item label="入库时间">
					<el-date-picker
						v-model="searchForm.stockInTimeRange"
						type="datetimerange"
						range-separator="至"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						value-format="YYYY-MM-DD HH:mm:ss"
						@change="handleSearch"
					/>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleSearch">
						<el-icon><search /></el-icon>
						查询
					</el-button>
					<el-button @click="handleReset">重置</el-button>
					<el-button type="primary" @click="handleRefresh">
						<el-icon><refresh /></el-icon>
						刷新
					</el-button>
				</el-form-item>
			</el-form>

			<div>
				<el-button @click="addRecord">新增</el-button>
				<el-button type="primary" @click="exportData" :loading="exportLoading"
					>导出</el-button
				>
			</div>

			<!-- 数据表格 -->
			<el-table
				border
				v-loading="loading"
				:data="tableData"
				style="width: 100%; margin-top: 20px"
				@selection-change="handleSelectionChange"
			>
				<el-table-column type="selection" width="55" />
				<el-table-column prop="itemCode" label="商品码" min-width="140" />
				<el-table-column prop="barcode" label="条形码" min-width="140" />
				<el-table-column prop="retailPrice" label="入库时零售价" min-width="140" sortable>
					<template #default="{ row }">
						¥{{ row.retailPrice?.toFixed(2) || '0.00' }}
					</template>
				</el-table-column>
				<el-table-column prop="quantity" label="数量" min-width="100" sortable />
				<el-table-column prop="stockInTime" label="入库时间" min-width="170" sortable>
					<template #default="{ row }">
						{{ formatDate(row.stockInTime) }}
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页 -->
			<div class="pagination-wrapper">
				<el-pagination
					v-model:current-page="pagination.page"
					v-model:page-size="pagination.size"
					:page-sizes="[10, 20, 50, 100]"
					:total="pagination.total"
					layout="total, sizes, prev, pager, next, jumper"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</div>
		</div>
		<add-form ref="addFormRef" @success="handleRefresh" />
	</el-card>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Refresh, Search } from '@element-plus/icons-vue';
import { useCool } from '/@/cool';
import { useI18n } from 'vue-i18n';
import AddForm from './component/add-form.vue';
import dayjs from 'dayjs';

defineOptions({
	name: 'stock-stock-in-record'
});

const { service } = useCool();
const { t } = useI18n();

// 响应式数据
const loading = ref(false);
const tableData = ref<any[]>([]);
const selectedRows = ref<any[]>([]);
const exportLoading = ref(false);

// 搜索表单数据
const searchForm = reactive({
	itemCode: '',
	barcode: '',
	stockInTimeRange: [] as string[]
});

// 分页数据
const pagination = reactive({
	page: 1,
	size: 10,
	total: 0
});

// 表单数据
const formData = reactive({
	itemCode: '',
	barcode: '',
	retailPrice: 0,
	quantity: 1,
	stockInTime: ''
});

// 表单引用
const formRef = ref();

// 表单验证规则
const formRules = {
	itemCode: [{ required: true, message: '请输入商品码', trigger: 'blur' }],
	barcode: [{ required: true, message: '请输入条形码', trigger: 'blur' }],
	retailPrice: [
		{ required: true, message: '请输入零售价', trigger: 'blur' },
		{ type: 'number', min: 0, message: '零售价不能小于0', trigger: 'blur' }
	],
	quantity: [
		{ required: true, message: '请输入数量', trigger: 'blur' },
		{ type: 'number', min: 1, message: '数量不能小于1', trigger: 'blur' }
	],
	stockInTime: [{ required: true, message: '请选择入库时间', trigger: 'change' }]
};

// 获取数据
const fetchData = async () => {
	loading.value = true;
	try {
		// 构建查询参数
		const params: any = {
			pageNum: pagination.page,
			pageSize: pagination.size
		};

		// 添加搜索条件
		if (searchForm.itemCode) {
			params.itemCode = searchForm.itemCode;
		}
		if (searchForm.barcode) {
			params.barcode = searchForm.barcode;
		}
		if (searchForm.stockInTimeRange && searchForm.stockInTimeRange.length === 2) {
			params.stockInTimeStart = searchForm.stockInTimeRange[0];
			params.stockInTimeEnd = searchForm.stockInTimeRange[1];
		}

		const pageData = await service.ling.pageStockInRecord(params);
		if (pageData && pageData.list) {
			tableData.value = pageData.list;
			pagination.total = pageData.pagination?.total || 0;
		} else {
			tableData.value = [];
			pagination.total = 0;
		}
	} catch (error) {
		console.error('获取数据失败:', error);
		ElMessage.error('获取数据失败');
		tableData.value = [];
		pagination.total = 0;
	} finally {
		loading.value = false;
	}
};

// 刷新数据
const handleRefresh = () => {
	fetchData();
};

// 搜索
const handleSearch = () => {
	pagination.page = 1;
	fetchData();
};

// 重置搜索表单
const handleReset = () => {
	searchForm.itemCode = '';
	searchForm.barcode = '';
	searchForm.stockInTimeRange = [];
	pagination.page = 1;
	fetchData();
};

// 分页大小改变
const handleSizeChange = (size: number) => {
	pagination.size = size;
	pagination.page = 1;
	fetchData();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
	pagination.page = page;
	fetchData();
};

// 选择改变
const handleSelectionChange = (selection: any[]) => {
	selectedRows.value = selection;
};

// 格式化日期
const formatDate = (date: string) => {
	if (!date) return '';
	return new Date(date).toLocaleString();
};

const addFormRef = ref();
const addRecord = () => {
	addFormRef.value.open('add');
};

// 组件挂载时获取数据
onMounted(() => {
	fetchData();
});

const exportData = async () => {
	try {
		// 构建查询参数
		const params: any = {
			pageNum: pagination.page,
			pageSize: pagination.size
		};

		// 添加搜索条件
		if (searchForm.itemCode) {
			params.itemCode = searchForm.itemCode;
		}

		if (searchForm.barcode) {
			params.barcode = searchForm.barcode;
		}

		// 调用导出接口
		exportLoading.value = true;
		const res = await service.request({
			url: '/admin/ling/exportStockInRecord',
			method: 'POST',
			data: params,
			responseType: 'blob'
		});

		// 创建下载链接
		const blob = new Blob([res], {
			type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
		});

		// 生成文件名
		const fileName = `入库记录_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`;

		// 创建下载链接并触发下载
		const url = window.URL.createObjectURL(blob);
		const link = document.createElement('a');
		link.href = url;
		link.download = fileName;
		document.body.appendChild(link);
		link.click();
		document.body.removeChild(link);
		window.URL.revokeObjectURL(url);

		ElMessage.success('导出成功');
	} catch (error) {
		console.error('导出失败:', error);
		ElMessage.error('导出失败，请重试');
	} finally {
		exportLoading.value = false;
	}
};
</script>
<style scoped>
.full-card {
	height: calc(100vh - 120px);
	overflow: auto;
}

.stock-product {
	padding: 20px;
}

.toolbar {
	display: flex;
	align-items: center;
	margin-bottom: 20px;
}

.flex-1 {
	flex: 1;
}

.pagination-wrapper {
	display: flex;
	justify-content: flex-end;
	margin-top: 20px;
}
</style>
